<template>
  <div class="app-container">
    <div class="search-bar">
      <!-- 拆线呢区域 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="区域名称" clearable style="width: 190px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="编码" prop="code">
          <el-input v-model="queryParams.code" placeholder="编码" clearable style="width: 190px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" icon="search" v-hasPerm="'sys_area_view'"
            @click="handleQuery()">
            搜索
          </el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <!-- 操作区域 -->
      <div class="mb-10px">
        <el-button type="success" icon="plus" v-hasPerm="'sys_area_add'" @click="handleOpenDialog()">新增</el-button>
        <!-- <el-button
          type="danger"
          :disabled="selectIds.length === 0"
          icon="delete"
          @click="handleDelete()"
        >
          删除
        </el-button> -->
      </div>
      <!-- @selection-change="handleSelectionChange" -->

      <el-table v-loading="loading" :data="deptList" row-key="id" height="calc(100vh - 350px)">
        <el-table-column prop="name" label="区域名称" min-width="200" />
        <el-table-column prop="code" label="区域编号" width="200" />
        <el-table-column prop="createBy" label="创建人" width="200" />
        <el-table-column prop="createTime" label="创建时间" width="200" />
        <el-table-column prop="updateBy" label="修改人" width="200" />
        <el-table-column prop="updateTime" label="更新时间" width="200" />
        <el-table-column label="操作" fixed="right" align="left" width="200">
          <template #default="scope">
            <el-button type="primary" link size="small" icon="edit" v-hasPerm="'sys_area_edit'"
              @click.stop="handleOpenDialog(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link size="small" icon="delete" v-hasPerm="'sys_area_del'"
              @click.stop="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div v-if="pageInfo.total > 0" class="pager-container">
        <pagination v-model:total="pageInfo.total" v-model:page="pageInfo.current" v-model:limit="pageInfo.size"
          @pagination="handleQuery" />
      </div>

    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.title" width="400px" @closed="handleCloseDialog">
      <el-form ref="deptFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="区域编号" prop="code">
          <el-input v-model="formData.code" placeholder="请输入区域编号" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: 'Dept',
  inheritAttrs: false,
});

import DeptAPI, { DeptVO } from '@/api/system/dept.api';
import { toRaw } from 'vue';
const queryFormRef = ref();
const deptFormRef = ref();

const loading = ref(false);
const selectIds = ref<number[]>([]);
const queryParams = reactive<DeptVO>({});
const pageInfo = reactive({
  current: 1,
  size: 10,
  total: 0,
});
const dialog = reactive({
  title: '新增',
  visible: false,
});
const deptList = ref<DeptVO[]>();
const formData = ref<DeptVO>({
  id: undefined,
  name: '',
  code: '',
});
watch(formData, () => {
  dialog.title = formData.value.id ? '编辑' : '新增';
});
const rules = reactive({
  name: [{ required: true, message: '区域名称不能为空', trigger: 'blur' }],
  code: [{ required: true, message: '区域编号不能为空', trigger: 'blur' }],
});

// 查询区域
function handleQuery({ page: current } = { page: 1 }) {
  loading.value = true;
  const param: any = {
    ...toRaw(queryParams),
    ...toRaw(pageInfo),
    current,
  };
  if (current) {
    pageInfo.current = current;
  }
  for (const key in param) {
    if (param[key] === undefined || param[key] === null || param[key] === '') {
      delete param[key];
    }
  }
  DeptAPI.getList(param).then((data: any) => {
    deptList.value = data.records;
    pageInfo.total = data.total;
    loading.value = false;
  });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

// 处理选中项变化
// function handleSelectionChange(selection: any) {
//   selectIds.value = selection.map((item: any) => item.id);
// }

/**
 * 打开区域弹窗
 *
 * @param parentId 父区域ID
 * @param deptId 区域ID
 */
async function handleOpenDialog(newDept?: DeptVO) {
  if (newDept) {
    formData.value = { ...newDept };
  }
  dialog.visible = true;
}

// 提交区域表单
function handleSubmit() {
  deptFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const deptId = <number>formData.value.id;
      if (deptId) {
        DeptAPI.update(formData.value)
          .then(() => {
            ElMessage.success('修改成功');
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        const param = { ...formData.value };
        delete param.id;
        DeptAPI.create(param)
          .then(() => {
            ElMessage.success('新增成功');
            handleCloseDialog();
            resetForm();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

// 删除区域
function handleDelete(deptId?: number) {
  const deptIds = [deptId || selectIds.value].join(',');

  if (!deptIds) {
    ElMessage.warning('请勾选删除项');
    return;
  }

  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(
    () => {
      loading.value = true;
      DeptAPI.deleteByIds(deptIds)
        .then(() => {
          ElMessage.success('删除成功');
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info('已取消删除');
    }
  );
}

// 重置表单
function resetForm() {
  deptFormRef.value.resetFields();
  deptFormRef.value.clearValidate();

  formData.value.id = undefined;
  formData.value.name = undefined;
  formData.value.code = undefined;
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  if (dialog.title === '编辑') {
    resetForm();
  }
}

onMounted(() => {
  handleQuery();
});
</script>
